package net.lwf.web.struts.exception;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.lwf.email.EmailNotification;
import net.lwf.exception.AppException;
import net.lwf.service.LwfService;
import net.lwf.util.SessionData;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;


public class WsExceptionHandler extends ExceptionHandler {

	public ActionForward execute(Exception ex, ExceptionConfig config,
			ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		String path = null;
		if (config.getPath() != null)
			path = config.getPath();
		else
			path = mapping.getInput();
		ActionForward forward = new ActionForward(path);
		ActionMessage error = null;
		String exceptionId = "";
		if (ex instanceof AppException) {
			AppException aex = (AppException) ex;
			exceptionId = aex.getUniqueID();
			request.setAttribute("exceptionID", exceptionId);
			error = new ActionMessage(config.getKey(), aex.getUniqueID());
		} else {
			request.setAttribute("exceptionID", "123456");
			error = new ActionMessage(config.getKey(),
					"no id: problem with struts configuration");
		}
		String property = error.getKey();
		storeException(request, property, error, forward, config.getScope());
		if(!LwfService.disableMail()) {
			EmailNotification.sendError(SessionData.getUserId(request), exceptionId);
		}
		return forward;
	}

}
